package com.miyu.system.service.sys.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miyu.common.pojo.cos.CosMenu;
import com.miyu.common.pojo.cos.CosSpace;
import com.miyu.common.utils.commonUtils.CommonUtils;
import com.miyu.system.dao.sys.CosMenuDao;
import com.miyu.system.dao.sys.CosSpaceDao;
import com.miyu.system.dao.sys.SysDao;
import com.miyu.system.service.sys.CosMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 菜单服务impl
 *
 * @author MIYU
 * @date 2022/05/14
 */
@Service
public class CosMenuServiceImpl implements CosMenuService {
    @Resource
    private CosMenuDao cosMenuDao;
    @Resource
    private CosSpaceDao cosSpaceDao;

    /**
     * 获取后台菜单
     * @return
     */
    @Override
    public JSONArray querySysMenu() {
        StringBuffer sql = new StringBuffer();
        sql.append(" select cm.menu_id, cm.component, cm.is_show, cm.is_stop, cm.is_sys, cm.menu_mod, cm.menu_name,cm.menu_icon, cm.path , cm.is_back," );
        sql.append("  cm.order_num, cm.parent_id,  cm.space_id,cm.space_id value, cm.is_last,cm.name ,cs.space_type ,cs.space_name from ");
        sql.append(" cos_menu cm ");
        sql.append(" left join cos_space cs on cm.space_id = cs.space_id ");
        JSONArray menus = cosMenuDao.queryJSONArrayBySql(sql.toString());
        //临时一级菜单
        JSONObject temp = new JSONObject();
        for (int i = 0; i < menus.size(); i++) {
            JSONObject jo = menus.getJSONObject(i);
            if(jo.getString("parentId").equals("-1")){
                /*所有一级菜单*/
                temp.put(jo.getString("menuId"),jo);
            }
        }
        JSONArray menuTree = new JSONArray();
        /*递归子菜单封装数据*/
        for (Map.Entry<String, Object> entry : temp.entrySet()) {
            /*一级菜单id*/
            JSONObject jo = (JSONObject) entry.getValue();
            JSONObject mate = new JSONObject();
            mate.put("title",jo.getString("menuName"));
            mate.put("keepAlive",true);
            jo.put("meta",mate);
            JSONArray jsonArray = getChild(jo,menus);
            if(jsonArray.size()>0){
                jo.put("children",jsonArray);
            }
            menuTree.add(jo);
        }
        /*一级菜单排序*/
        menuTree.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
        return menuTree;
    }

    /**
     * 递归子菜单
     * @param jo
     * @param menus
     * @return
     */
    private JSONArray getChild(JSONObject jo, JSONArray menus) {
        JSONArray children = new JSONArray();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
        jo.put("children",children);
        for (int i = 0; i < menus.size(); i++) {
            JSONObject temp = menus.getJSONObject(i);
            if(temp.getString("parentId").equals(jo.getString("menuId"))){
                /*额外配置meta*/
                JSONObject mate = new JSONObject();
                mate.put("title",temp.getString("menuName"));
                temp.put("meta",mate);
                children.add(temp);
                /*排序*/
                children.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
                /*递归*/
                getChild(temp,menus);
            }
        }
        // 当遍历完成，返回调用的父节点的所有子节点
        return children;

    }

    @Override
    public JSONArray getMenuDict(JSONObject param) {
        StringBuffer sql = new StringBuffer();
        sql.append(" select cm.menu_id  , menu_name ," );
        sql.append("  cm.order_num, cm.parent_id  from ");
        sql.append(" cos_menu cm ");
        sql.append(" left join cos_space cs on cm.space_id = cs.space_id ");
        if(param.getString("spaceId")!=null){
            sql.append(" where cm.space_id = '"+param.getString("spaceId")+"' ");
        }
        JSONArray menus = cosMenuDao.queryJSONArrayBySql(sql.toString());
        /*一级菜单排序*/
        menus.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
        System.out.println(menus);
        return menus;
    }

    @Override
    public List<CosSpace> getCosSpaceList() {
        return cosSpaceDao.findAll();
    }
    /**
     * 保存或修改菜单
     * @param param
     * @return
     */
    @Override
    public JSONObject SaveOrUpdateSysMenu(JSONObject param) {
        CosMenu cosMenu = new CosMenu();
        System.out.println(param);
        if(param.containsKey("menuId")){
            /*当前修改数据信息*/
            cosMenu = cosMenuDao.findById(param.getString("menuId")).get();
            /*修改*/
            cosMenu.setMenuId(param.getString("menuId"));
            cosMenu.setMenuName(param.getString("menuName"));
            cosMenu.setPath(param.getString("path"));
            cosMenu.setIsStop(param.getString("isStop"));
            cosMenu.setMenuIcon(param.getString("menuIcon"));
            cosMenu.setOrderNum(param.getInteger("orderNum"));
            cosMenu.setMome(param.getString("mome"));
            cosMenu.setName(param.getString("name"));
            if(param.containsKey("component")) {
                cosMenu.setComponent(param.getString("component"));
            }
            if(param.containsKey("spaceId")) {
                cosMenu.setSpaceId(param.getString("spaceId"));
            }
            cosMenuDao.saveOrUpdateByNotNullProperties(cosMenu);
        }else{
            /*新增*/
            StringBuffer sql = new StringBuffer();
            String menuId = CommonUtils.getUUID();
            cosMenu.setMenuId(menuId);
            cosMenu.setMenuName(param.getString("menuName"));
            cosMenu.setPath(param.getString("path"));
            /*非末级可不填写*/
            if(param.containsKey("component")) {
                cosMenu.setComponent(param.getString("component"));
            }
            if(param.containsKey("spaceId")) {
                cosMenu.setSpaceId(param.getString("spaceId"));
            }
            cosMenu.setIsStop(param.getString("isStop"));
            cosMenu.setMenuIcon(param.getString("menuIcon"));
            cosMenu.setOrderNum(param.getInteger("orderNum"));
            cosMenu.setMome(param.getString("mome"));
            cosMenu.setName(param.getString("name"));
            cosMenu.setIsBack("1");
            cosMenu.setIsLast("1");
            cosMenu.setIsSys("0");
            if(param.containsKey("parentId")&&param.getString("parentId").length()>0){
                cosMenu.setParentId(param.getString("parentId"));
                sql.append("update cos_menu set is_last='0' where menu_id='"+cosMenu.getParentId()+"'");
            }else {
                cosMenu.setParentId("-1");
            }
            /*父级菜单自动更新为非末级菜单*/
            if (sql.length() > 0) {
                cosMenuDao.update(sql.toString());
            }
            cosMenuDao.save(cosMenu);

        }
        JSONObject json = new JSONObject();
        json.put("code",0);
        json.put("msg","保存成功");
        return json;
    }

    /**
     * 菜单删除 只可删除菜单下没有末级的菜单 非末级不可删除
     * @param param
     * @return
     */
    @Override
    public JSONObject delCosMenu(JSONObject param) {
        System.out.println(param);
        System.out.println(param.getString("isLast"));
        if("1".equals(param.getString("isLast"))){
            cosMenuDao.deleteById(param.getString("menuId"));
        }else{
            List<CosMenu> cosMenus = cosMenuDao.findById(param.getString("menuId")).stream().toList();
            StringBuffer sql = new StringBuffer();
            sql.append("from CosMenu where parentId='"+param.getString("menuId")+"'");
            List<CosMenu> cosMenuList = cosMenuDao.queryListByHql(sql.toString());
            /*先删除子菜单*/
           cosMenuDao.deleteAll(cosMenuList);
           /*再删除当前菜单*/
            cosMenuDao.deleteById(param.getString("menuId"));
        }
        JSONObject json = new JSONObject();
        json.put("code",0);
        json.put("msg","删除成功");
        return json;
    }

}
